var id;

// 选择ztree
var setting = {
  check: {
    enable: true
  },
  data: {
    simpleData: {
      enable: false
    }
  },
  view: {
    showIcon: false
	},
	callback: {
		onCheck: zTreeOnCheck
	}
};

/**标准数据格式*/
var zNodes = [];

// 选中的zTree值
var participantId = [];

$(function() {
  $(".validform").createForm();
  id = ly.getUrlParam("id") || '';
  if (id) {
    $(".body_title").html("编辑");
    $(".form").getForm({
      id: id,
      ajaxform: true,
    }, function(data) {
      selectbusinessList(data.equipmentId);
      $("#isUsing").getSelect({
        type: "radio",
        asName: "isUsing",
        list: [
          { value: "1", display: "启用" },
          { value: "0", display: "禁用" }
        ],
        default: data.isUsing
			});

      if(data.attendancePersonnel&&data.attendancePersonnel.length){
        var currStr='';
        for (var i = 0; i < data.attendancePersonnel.length; i++) {
          var usersInfo = data.attendancePersonnel[i];
          if(i==data.attendancePersonnel.length-1){
            currStr +=usersInfo.nickName+"&nbsp;&nbsp;&nbsp;&nbsp;";
          }else{
            currStr +=usersInfo.nickName+'、'
          }
        }
        $(".addboxlist").html(currStr);
      }
			getTeamUser(data.attendancePersonnel); // 获取部门与人员集合
			$("#attendanceStartTime").val(data.attendanceStartTime + ':00'); // 考勤开始时间
			$("#attendanceEndTime").val(data.attendanceEndTime + ':00'); // 考勤结束时间
    });
  } else {
    selectbusinessList("");
    $("#isUsing").getSelect({
      type: "radio",
      asName: "isUsing",
      list: [
        { value: "1", display: "启用" },
        { value: "0", display: "禁用" }
      ],
      default: '1'
		});
		getTeamUser(); // 获取部门与人员集合

  }
  //获取到选择的值
  $("body").on("click", "input[name='userType']", function() {
    var userType = this.value;
    if (userType == '2') {
      $("#changeBusinessId").removeClass("hide");
      selectbusinessList(businessId);
    } else {
      $("#changeBusinessId").addClass("hide");
    }
  });

  //提交
  $("body").on("click", "#save-btn-commodityClassification", function(event) {
    event.preventDefault();
    var success = $('.form').validate('submitValidate');
    var checkingInName = $("#checkingInName").val(); // 考勤名称
    var attendanceRange = parseFloat( $("#attendanceRange").val()); // 考勤范围
    var attendanceStartTime = $("#attendanceStartTime").val(); // 考勤开始时间
    var attendanceEndTime = $("#attendanceEndTime").val(); // 考勤结束时间
    var equipmentId = $('select[name=equipmentId] option:checked').val(); // 考勤设备
    var isUsing = $("#isUsing input[name=isUsing]:checked").val(); // 是否启用(0:否;1:是)

		var attendanceDays = ''; // 考勤工作日
		$.each($("#attendanceDays input[name=attendanceDays]:checked"), function(i, o) {
			attendanceDays += $(o).val() + ',';
		})
		attendanceDays = attendanceDays.substr(0, attendanceDays.length - 1);
		
		// 获取选中人员Id集合
		var participantIdArr = participantId.toString();

    //验证通过提交表单
    if (attendanceEndTime < attendanceStartTime) {
      ly.toast('考勤结束时间应在开始时间之后');
      return;
		}
		
		if (participantIdArr == '') {
			ly.toast('请选择考勤人员');
      return;
		}

    if (success) {
      var obj = {};
      var url = site.apiUrl + "/back/attendanceManagement/insertOrUpdateAttendanceManagement";
      if (id) {
        //修改
        obj = {
          'checkingInName': checkingInName,
          'attendanceRange': attendanceRange,
          'attendanceStartTime': attendanceStartTime,
          'attendanceEndTime': attendanceEndTime,
          'equipmentId': equipmentId,
          'isUsing': isUsing,
          "attendanceDays": attendanceDays,
					'id': id,
					'participantId': participantIdArr,
        };
      } else {
        //新增
        obj = {
          'checkingInName': checkingInName,
          'attendanceRange': attendanceRange,
          'attendanceStartTime': attendanceStartTime,
          'attendanceEndTime': attendanceEndTime,
          'equipmentId': equipmentId,
          'attendanceDays': attendanceDays,
					'isUsing': isUsing,
					'participantId': participantIdArr,
        };
      }
      request({
        url: url,
        data: obj,
        type: "post",
        callback: function(f) {
          if (f.code == "rest.success") {
            if (id == '') {
              ly.alert('保存成功', function() {
                ly.goto("attendanceManagement-list.html");
              });
            } else {
              ly.alert('修改成功', function() {
                ly.goto("attendanceManagement-list.html");
              });
            }
          } else {
            ly.toast(f.desc);
          }
        }
      });

    }
  })

  //批量删除
  $("#batchDelBtn").click(function() {
    var c = "";
    $("input[name=datachk]:checked").each(function() {
      c += $(this).val() + ',';
    });
    deleteFirstCategory(c);
  });

	// 点击显示--选择部门人员弹窗
  $("#changePerson").on("click", function() {
    var index = layer.open({
      title: false,
      type: 1,
      area: ['600px'], //设置宽度,高度自适应
      closeBtn: 0,
      content: $(".layerBox"),
      success: function(layero, index) {
        $("#layui-layer" + index).find(".goback,.icon-close").on("click", function() {
					layer.close(index);
        });
        $("#sayerBox-btn").on("click", function() {
					getzTreeChecked();
					ly.toast('选择成功','',500)
					layer.close(index);
        })
      }
    });
  })
});

// zTree发生改变
function zTreeOnCheck(event, treeId, treeNode) {
	var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo"); // ztree的Id
  var checkedNodes = zTreeObj.getCheckedNodes();
	$("#ztreeCheckedNames").html('');
	for(var i = 0; i < checkedNodes.length; i++) {
    if (!checkedNodes[i].children) {
      $("#ztreeCheckedNames").append('<li>'+ checkedNodes[i].name +'</li>')
    }
  }
};

// 获取zTree选中的值
function getzTreeChecked() {
	participantId = [];
  var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo"); // ztree的Id
	var checkedNodes = zTreeObj.getCheckedNodes();
  var currStr='';
	$.each(checkedNodes, function(i, o) {
		if (checkedNodes[i].userId) {
			participantId.push(checkedNodes[i].userId);
      if(i==checkedNodes.length-1){
        currStr +=checkedNodes[i].name+"&nbsp;&nbsp;&nbsp;&nbsp;";
      }else{
        currStr +=checkedNodes[i].name+'、';
      }
		}
	})
  $(".addboxlist").html(currStr);
}

//选择参考人选弹出窗
function changePerson() {}

function countDown(time) {
  var s = 0;
  var hour = time.split(':')[0];
  var min = time.split(':')[1];
  var sec = time.split(':')[2];
  s = Number(hour * 3600) + Number(min * 60) + Number(sec);
  return s;
};

// 获取考勤机
function selectbusinessList(equipmentId) {
  var list = new Array();
  request({
    url: site.apiUrl + "/back/attendanceBack/selectEquipmentListBack",
    data: { 'num': 1, 'size': 100, 'isUsing': 1, 'equipmentType': 1 },
    type: "get",
    ajaxform: true,
    callback: function(f) {
      if (f.code == "rest.success") {
        var obj = { value: ' ', display: '请选择' };
        list.push(obj);
        if (f.result.list != null && f.result.list != '') {
          obj = {};
          $.each(f.result.list, function(i, o) {
            obj = { value: o.id, display: o.equipmentName };
            list.push(obj);
          });
        }
        $("#equipmentId").getSelect({
          type: "select",
          asName: "equipmentId",
          list: list,
          default: equipmentId
        });
      }
    }
  });
}

// 获取部门与人员集合
function getTeamUser(viewData) {
	request({
    url: site.apiUrl + "/back/team/selectTeamUserByGroupsBack",
    type: "get",
    callback: function(f) {
      if (f.code == "rest.success") {
				zNodes = f.result;
				if (!viewData) { // 新增
					$("#ztreeCheckedNames").html('');
					$.fn.zTree.init($("#treeDemo"), setting, zNodes); // 加载ztree
					var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo"); // ztree的Id
					zTreeObj.checkAllNodes(false); // 清除所有节点选中状态
					zTreeObj.expandAll(false); // 收起所有节点
        } else { // 编辑
					var viewCheckedPerson = zNodes.map(function (item) {
						if (item.children && item.children.length > 0) {
							var childrenCheckOption = item.children;
							var newChildren = childrenCheckOption.map(function (itm) {
								// 判断选中项，true设置cheked=true，反之设为false
								var isCheckedOption = viewData.some(function (items) {
									return items.userId === itm.userId;
								});
								if (isCheckedOption) {
									itm.checked = true; // 为true时zTree勾选当前项
								} else {
									itm.checked = false;
								}
								return itm;
							});
							item.children = newChildren;
							return item;
						} else {
              return item;
            }
					});
					$.fn.zTree.init($("#treeDemo"), setting, viewCheckedPerson); // 加载ztree
					var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo"); // ztree的Id
					zTreeObj.expandAll(false); // 收起所有节点
          zTreeOnCheck(); // 展示右侧选中项
          
          // 设置编辑默认选中值
          participantId = [];
          $.each(viewData, function(i, o) {
            participantId.push(viewData[i].userId);
          })
				}
      }
    }
  });
}